package com.imay.live.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 倒计时控件
 * Created by lzx on 2017/06/23 0023.
 */

public class CountdownView extends ImageView {
    private ObjectAnimator objectAnimator = new ObjectAnimator();

    public CountdownView(Context context) {
        super(context);
    }

    public CountdownView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CountdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CountdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void start(final TimeListener timeListener, AnimationDrawable drawable) {
        if (drawable == null || drawable.getNumberOfFrames() == 0) {
            if (timeListener != null) {
                timeListener.onEnd();
            }
            return;
        }
        long duration = 0;
        for (int i = 0; i < drawable.getNumberOfFrames(); i++) {
            duration = duration + drawable.getDuration(i);
        }
        objectAnimator.setIntValues(0, drawable.getNumberOfFrames());
        objectAnimator.setDuration(duration);
        objectAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
//                if (timeListener != null) {
//                    timeListener.start();
//                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (timeListener != null) {
                    timeListener.onEnd();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        drawable.start();
        objectAnimator.start();
    }

    public void start(final TimeListener timeListener) {
        AnimationDrawable drawable = (AnimationDrawable) getDrawable();
        start(timeListener, drawable);
    }

    public interface TimeListener {
//        void onStart();
        void onEnd();
    }
}
